﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Deferred.Library.Configuration;

namespace Deferred.Editor.Gui
{
    public partial class OptionsPanel : UserControl
    {
        private static readonly int CheckBoxPosition = 8;
        private static readonly int CheckBoxYHeight = 23;
        private static readonly int CheckBoxPadding = 3;

        Dictionary<string, TabPage> categoryToTabPage = new Dictionary<string, TabPage>();
        Dictionary<string, CheckBox> fullNameToCheckBox = new Dictionary<string, CheckBox>();

        private IOptions options;

        public OptionsPanel(IOptions options)
        {
            InitializeComponent();

            this.options = options;
            options.OptionAdded += new OptionAddedEvent(AddOption);

            foreach (Option option in options.GetOptions())
            {
                AddOption(option);
            }
        }

        public void AddOption(Option option)
        {
            TabPage page = GetTabPage(option.Category);

            CheckBox checkbox = new CheckBox();
            checkbox.Text = option.FullName;
            checkbox.Name = option.FullName;
            checkbox.Checked = option.Value;
            checkbox.AutoCheck = true;
            checkbox.TabIndex = this.Controls.Count;
            checkbox.Location = new System.Drawing.Point(CheckBoxPosition, CheckBoxPosition + CheckBoxYHeight * page.Controls.Count);
            checkbox.Size = new System.Drawing.Size(this.Size.Width - 2 * CheckBoxPosition, CheckBoxYHeight - 2 * CheckBoxPadding);
            checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);

            fullNameToCheckBox.Add(option.FullName, checkbox);
            option.ValueChanged += new OptionChangedEvent(option_ValueChanged);

            page.Controls.Add(checkbox);
        }

        void option_ValueChanged(Option sender, bool value)
        {
            fullNameToCheckBox[sender.FullName].Checked = value;
        }

        private TabPage GetTabPage(string category)
        {
            if (!categoryToTabPage.ContainsKey(category))
            {
                TabPage page = new TabPage(category);
                page.AutoScroll = true;
                categoryTabs.TabPages.Add(page);
                categoryToTabPage.Add(category, page);
            }

            return categoryToTabPage[category];
        }

        void checkbox_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkbox = (CheckBox)sender;
            options[checkbox.Name] = checkbox.Checked;
        }
    }
}
